<template>
    <div class="dashboard-container">
        <h2>仪表盘</h2>

        <!-- 统计卡片 -->
        <el-row :gutter="20" class="stats-row">
            <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
                <el-card class="stat-card">
                    <div class="stat-content">
                        <div class="stat-icon active">
                            <el-icon>
                                <Clock />
                            </el-icon>
                        </div>
                        <div class="stat-info">
                            <div class="stat-number">{{ stats.activeCount }}</div>
                            <div class="stat-label">活跃任务</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
                <el-card class="stat-card">
                    <div class="stat-content">
                        <div class="stat-icon paused">
                            <el-icon>
                                <VideoPause />
                            </el-icon>
                        </div>
                        <div class="stat-info">
                            <div class="stat-number">{{ stats.pausedCount }}</div>
                            <div class="stat-label">暂停任务</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
                <el-card class="stat-card">
                    <div class="stat-content">
                        <div class="stat-icon stopped">
                            <el-icon>
                                <VideoPlay />
                            </el-icon>
                        </div>
                        <div class="stat-info">
                            <div class="stat-number">{{ stats.stoppedCount }}</div>
                            <div class="stat-label">停止任务</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
                <el-card class="stat-card">
                    <div class="stat-content">
                        <div class="stat-icon total">
                            <el-icon>
                                <Document />
                            </el-icon>
                        </div>
                        <div class="stat-info">
                            <div class="stat-number">{{ stats.totalCount }}</div>
                            <div class="stat-label">总任务数</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 最近执行的任务 -->
        <el-card class="recent-tasks-card" shadow="never">
            <template #header>
                <div class="card-header">
                    <span>最近执行的任务</span>
                    <el-button type="primary" @click="goToTaskList">查看全部</el-button>
                </div>
            </template>

            <el-table :data="recentTasks" stripe style="width: 100%" class="fixed-table">
                <el-table-column prop="taskName" label="任务名称" min-width="150" />
                <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="executionCount" label="执行次数" width="100" />
                <el-table-column prop="lastExecutedAt" label="最后执行时间" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.lastExecutedAt) }}
                    </template>
                </el-table-column>
                <el-table-column prop="nextExecutionAt" label="下次执行时间" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.nextExecutionAt) }}
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Clock, VideoPause, VideoPlay, Document } from '@element-plus/icons-vue'
import { jobTaskApi } from '@/api/jobs'

const router = useRouter()

// 统计数据
const stats = reactive({
    activeCount: 0,
    pausedCount: 0,
    stoppedCount: 0,
    totalCount: 0
})

// 最近执行的任务
const recentTasks = ref([])

// 加载统计数据
const loadStats = async () => {
    try {
        const response = await jobTaskApi.getAllTasks()
        const tasks = response.data || []

        stats.totalCount = tasks.length
        stats.activeCount = tasks.filter(task => task.status === 'ACTIVE').length
        stats.pausedCount = tasks.filter(task => task.status === 'PAUSED').length
        stats.stoppedCount = tasks.filter(task => task.status === 'STOPPED').length

        // 获取最近执行的任务 (按最后执行时间排序，取前5个)
        const tasksWithExecution = tasks.filter(task => task.lastExecutedAt)
        tasksWithExecution.sort((a, b) => new Date(b.lastExecutedAt) - new Date(a.lastExecutedAt))
        recentTasks.value = tasksWithExecution.slice(0, 5)

    } catch (error) {
        console.error('加载统计数据失败:', error)
    }
}

// 跳转到任务列表
const goToTaskList = () => {
    router.push('/jobs')
}

// 获取状态标签类型
const getStatusType = (status) => {
    const typeMap = {
        ACTIVE: 'success',
        PAUSED: 'warning',
        STOPPED: 'danger'
    }
    return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const textMap = {
        ACTIVE: '活跃',
        PAUSED: '暂停',
        STOPPED: '停止'
    }
    return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return '-'
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    })
}

// 组件挂载时加载数据
onMounted(() => {
    loadStats()
})
</script>

<style scoped>
.dashboard-container {
    padding: 0 20px;
    width: 100%;
    box-sizing: border-box;
}

.dashboard-container h2 {
    margin: 0 0 15px 0;
    color: #303133;
    padding: 0 5px;
}

.stats-row {
    margin-bottom: 15px;
}

.stat-card {
    border-radius: 8px;
}

/* 统计卡片内容 */
.stat-content {
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;
}

.stat-icon.active {
    background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-icon.paused {
    background: linear-gradient(135deg, #e6a23c, #f0c473);
}

.stat-icon.stopped {
    background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-icon.total {
    background: linear-gradient(135deg, #409eff, #73b9ff);
}

.stat-info {
    flex: 1;
}

.stat-number {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    line-height: 1;
}

.stat-label {
    font-size: 14px;
    color: #909399;
    margin-top: 5px;
}

/* 最近任务卡片 */
.recent-tasks-card {
    border-radius: 8px;
    width: 100%;
}

.recent-tasks-card :deep(.el-card__body) {
    padding: 15px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 表格优化 */
:deep(.el-table) {
    width: 100% !important;
}

/* 表格水平滚动 */
.fixed-table {
    overflow-x: auto;
}

:deep(.fixed-table .el-table__body-wrapper) {
    overflow-x: auto;
}

/* 响应式布局 */


@media (max-width: 768px) {
    .dashboard-container {
        padding: 0 10px;
    }

    .stats-row {
        margin-bottom: 10px;
    }

    .stat-content {
        gap: 10px;
    }

    .stat-icon {
        width: 40px;
        height: 40px;
        font-size: 20px;
    }

    .stat-number {
        font-size: 24px;
    }

    .stat-label {
        font-size: 12px;
    }

    .card-header {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
    }

    .card-header .el-button {
        align-self: flex-end;
    }
}

@media (max-width: 480px) {
    .dashboard-container h2 {
        font-size: 18px;
        margin-bottom: 10px;
    }

    .stat-content {
        flex-direction: column;
        text-align: center;
        gap: 8px;
    }

    .stat-icon {
        width: 35px;
        height: 35px;
        font-size: 18px;
        margin: 0 auto;
    }

    .stat-number {
        font-size: 20px;
    }

    .stat-label {
        font-size: 11px;
    }

    /* 表格在移动端的优化 */
    :deep(.el-table) {
        font-size: 12px;
    }

    :deep(.el-table .el-table__cell) {
        padding: 8px 4px;
    }

    :deep(.el-table .cell) {
        word-break: break-all;
    }
}
</style>